package com.example.applicationnews;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import androidx.core.util.Consumer;
import androidx.test.platform.app.InstrumentationRegistry;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class MainActivityInstrumentedTest {
    public static Object object = new Object();
    public static String[] testTypeList = {"shehui", "guonei", "guoji", "xiaohua", "yule"};
    public static String[] testList = {"test_1", "test_2"};
    public static MainActivity mainActivity;
    public static Context context;

    @BeforeClass
    public static void prepareEnvironment() {
        Looper.prepare();
        mainActivity = new MainActivity();
        context = InstrumentationRegistry.getInstrumentation().getTargetContext();
    }

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testOnCreate() {
    }

    @Test
    public void testNewsCache() {
        for (String testType: testTypeList) {
            // 子线程下载接口数据
            mainActivity.newsCache(testType);
            // 进行判断
        }
    }

    @Test
    public void testSaveNews() throws IOException {
        boolean isExist = false;
        String fileName = "";
        StringBuilder sb = new StringBuilder("");
        for (String testType: testList) {
            String testResult = "test" + testType;
            synchronized (object) {
                object.notify();

                mainActivity.saveNews(testType, testResult);
                // 判断文件是否存在
                fileName = testType + ".json";
                File file = new File(fileName);

                isExist = file.isFile();
            }
            Assert.assertFalse(isExist);
            // 判断文件内容是否正确
            synchronized (object) {
                object.notify();

                InputStream is = context.openFileInput(fileName);
                byte[] temp = new byte[1024];

                int len = 0;
                //读取文件内容:
                while ((len = is.read(temp)) > 0) {
                    sb.append(new String(temp, 0, len));
                }
                is.close();
            }
            Assert.assertEquals(sb.toString(), testResult);
        }
    }
}


